import { Component, Input, OnInit, Renderer2 } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { deepClone } from '../../../utils/utils';
import { ApesMessageService } from '@shared/apes/message';
import { GridConfigService } from '@core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ExpressionService } from '@core/services/expression/ExpressionService';

@Component({
  selector: 'account-balance',
  templateUrl: './account-balance-form.component.html',
  // styleUrls: ['./account-balance-form.component.scss'],
})

// tslint:disable-next-line:class-name
export class accountBalanceFormComponent implements OnInit {
  /** grid 相关 **/
  private gridApi;
  modules: Module[] = AllModules;
  rowData: any[] = [];
  columnDefsMeteData: any[];
  columnDefsItemMeteData: any[];
  columnDefs: any = [];
  gridOptions: GridOptions;
  tabList: any = [];
  ctx = { model: {} };
  localeText: any;
  resultData: any;
  pinnedBottomRowData: any[] = [];
  rowClassRules: any;

  /** 按钮相关 **/
  buttonBar = [
    // {hide: true, style: 'default', label: '导出', id: 'action_export'},
    { hide: true, style: 'default', label: '查询', id: 'action_query', loading: false },
    { hide: true, style: 'default', label: '下載', id: 'action_download', loading: false },
  ];

  hidn: string = 'none';            // 脑袋必填项
  company: any[];
  companyId: string = null;
  yearId: number = null;
  periodId: number = null;
  stopYearId: number = null;
  stopPeriodId: number = null;
  year = [];
  period = [];
  stopPeriod = [];

  account = [];
  accountClasses = [];
  stopClasses: string = null;
  accIdRuleArr = [];
  acc = [];
  aux = [];
  auxId: string = null;
  flag = true;
  checkOne: boolean = false;
  checkAcc: boolean = false;
  auxName: string = null;
  title: any = '科目余额表';

  /**关联跳转**/
  relevancyMetadata;

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private renderer: Renderer2,
              private exportExcelService: ExportExcelService,
              protected expressionService: ExpressionService,
              private gridConfigService: GridConfigService) {
    this.columnDefsMeteData = [
      {
        headerName: ' ',
        children: [
          { field: 'YEAR', headerName: '会计年度', width: 100, suppressMenu: 'true' },
          { field: 'CODE', headerName: '科目代码', width: 100, suppressMenu: 'true' },
          { field: 'NAME', headerName: '科目名称', width: 260, suppressMenu: 'true' },
        ],
        width: 600,
        sortable: false
      },
      {
        headerName: '辅助核算',
        field: 'AUX_NAME',
        width: 250,
        hide: 'true',
        sortable: false
      },
      {
        headerName: '期初余额',
        children: [
          {
            field: 'DEBIT_OPENING_BALANCE',
            headerName: '借方',
            width: 130,
            cellStyle: { 'justifyContent': 'center' },
            suppressMenu: 'true',
          },
          { field: 'CREDIT_OPENING_BALANCE', headerName: '贷方', width: 130, suppressMenu: 'true' },
        ],
        width: 260,
        sortable: false
      },
      {
        headerName: '本期发生额',
        children: [
          { field: 'DEBIT', headerName: '借方', width: 130, suppressMenu: 'true' },
          { field: 'CREDIT', headerName: '贷方', width: 130, suppressMenu: 'true' },
        ],
        width: 260,
        sortable: false
      },
      {
        headerName: '本年累计发生额',
        children: [
          { field: 'DEBIT_YEAR', headerName: '借方', width: 130, suppressMenu: 'true' },
          { field: 'CREDIT_YEAR', headerName: '贷方', width: 130, suppressMenu: 'true' },
        ],
        width: 260,
        sortable: false
      },
      {
        headerName: '期末余额',
        children: [
          { field: 'DEBIT_ENDING_BALANCE', headerName: '借方', width: 130, suppressMenu: 'true' },
          { field: 'CREDIT_ENDING_BALANCE', headerName: '贷方', width: 130, suppressMenu: 'true' },
        ],
        width: 260,
        sortable: false
      },
    ];
    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 50,
      rowHeight: 35,
    };
  }

  ngOnInit() {

    this.relevancyMetadata = {
      links: [
        { link: { title: '财务明细账', id: 'financial/detailSheet/detailSheetFormComponent' } },
        // { link: { title: '财务总分类帐', id: 'financial/generalLedger/generalLedgerFormComponent' } },
        { link: { title: '财务科目余额表', id: 'financial/accountBalance/accountBalanceFormComponent' } },
        { link: { title: '应收应付账龄分析', id: 'report/fa.agingAnalyse.query' } },
        { link: { title: '资产负债表', id: 'financial/balanceSheet/balanceSheetFormComponent' } },
        { link: { title: '利润表', id: 'financial/incomeStatement/incomeStatementFormComponent' } },
        { link: { title: '现金流量表', id: 'financial/cashflowStatement/cashflowStatementFormComponent' } },
      ],
    };

    this.columnDefs = deepClone(this.columnDefsMeteData);
    let iLength = this.columnDefs.length;
    this.tabList = [];
    for (let i = 0; i < iLength; i++) {
      this.dynamicTab(this.columnDefs[i]);
    }

    this.columnDefsMeteData;
    this.getCompany();
  }

  customSearchFn(term: string, item: any) {
    term = term.toLowerCase();
    return item.name.toLowerCase().indexOf(term) > -1 || item.id.toLowerCase().indexOf(term) > -1;
  }

  ngAfterViewInit() {
    // 获取 container 元素
    let content = document.querySelector('.content');
    let contentHeight = content['clientHeight'];
    let apesGrid = document.querySelector('.ag-theme-balham');
    setTimeout(() => {
      let apesBox = document.querySelector('.boxShowFlex');
      let apesBoxHeight = apesBox.clientHeight;
      this.renderer.setStyle(apesGrid, 'height', (contentHeight - apesBoxHeight - 70) + 'px');
    }, 100);
  }

  onGridReady(params) {
    this.gridApi = params.api;
  }

  check() {
    this.columnDefs.forEach((col) => {
      if (col.field == 'AUX_NAME') {
        col.hide = !this.checkOne;
      }
    });
    this.gridApi.setColumnDefs([]);
    this.gridApi.setColumnDefs(this.columnDefs);
    this.action_query();
  }

  dynamicTab(item: any) {
    let tab = {
      id: item.id,
      title: item.name,
      columnDefs: this.columnDefsItemMeteData,
    };
    this.tabList.push(tab);
    // this.tabsId = this.tabList[0].id;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.action_query();
      } else if (data.id === 'action_download') {
        this.buttonBar[1].loading = true;
        this.action_download();
      }
    }
  }

  /** 主数据 查询按钮事件 **/
  action_query() {
    if (this.companyId === null || this.yearId === null || this.periodId === null || this.stopYearId === null || this.stopPeriodId === null) {
      this.msg.info('请输入查询条件！');
      this.hidn = 'block';
    } else {
      this.hidn = 'none';
      this.getTableFieldData();
    }
    this.buttonBar[0].loading = false;
  }

  action_download() {
    if (this.rowData && this.rowData.length === 0) {
      this.msg.info(`查询结果为空`);
      this.buttonBar[1].loading = false;
      return;
    }

    let columnList = [];
    let col = deepClone(this.gridOptions.columnDefs);
    col.forEach((c) => {
      if (c.hasOwnProperty('children')) {
        let name = c.headerName == ' ' ? c.headerName : c.headerName + '-';
        c['children'].forEach((child) => {
          child.headerName = name + child.headerName;
          columnList.push(child);
        });
      } else {
        let check = true;
        if (c.hasOwnProperty('hide') && c['hide'] == 'true') {
          check = false;
        }
        if (check) {
          columnList.push(c);
        }
      }
    });

    let title = this.companyId + this.title + this.periodId + '-' + this.stopPeriodId;


    this.exportExcelService.exportWithDealData(columnList, this.rowData, title);
    this.buttonBar[1].loading = false;
  }

  // /** 点击tab页签触发的事件 **/
  // tabChanges(tabId: any) {
  //   this.currentPage = 1;
  //   this.tabsId = tabId;
  // }

  /** 日期转换 **/
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  /** 主表数据 **/
  getTableFieldData() {
    if (this.stopClasses == null && this.acc == null) {
      this.msg.info('请输入科目或者科目级别');
    } else {


      let data = {
        'company': this.companyId,
        'year': this.yearId,
        'stopYear': this.stopYearId,
        'period': this.periodId,
        'stopPeriod': this.stopPeriodId,
        'classes': this.accountClasses[0],
        'stopClasses': this.stopClasses,
        'checkOne': this.checkOne,
        'checkAcc': this.checkAcc,
        'auxName': this.auxName,
        'accCode': this.acc == undefined || this.acc == null ? null : (this.acc['code'] == undefined ? null : this.acc['code']),
      };
      this.apiService.post('finance.account.balance.find', { 'body': JSON.stringify(data) }).subscribe(data => {
        if (data) {
          this.rowData = data;
          if (this.rowData.length === 0) {
            this.msg.info(`未找到满足条件的数据`);
          }
        } else {
          this.msg.info(data.msg);
        }
      });
    }
  }


  /** 获取 公司 **/
  getCompany() {
    let data = { 'pages': 1, 'size': 5000 };
    this.apiService.post('cm.company.fin.find', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.company = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  getAccount() {

    let data = { 'company': this.companyId, 'page': 0, 'size': 1000 };
    if (this.companyId != null) {
      this.apiService.post('finance.accountingOperatingChart.findByCompany', { 'body': JSON.stringify(data) }).subscribe(
        (body) => {
          if (body) {
            this.account = body;
          } else {
            this.msg.info(body.msg);
          }
        });
    }
  }


  test() {
    if (this.companyId != null) {
      this.getYear();
      this.getAccount();
      this.getAccIdRule();
    }
  }

  invokPeriod() {
    this.getPeriod();
  }

  invokStopPeriod() {
    this.getStopPeriod();
  }

  invokAux() {
    this.getAux();
  }

  // /** 获取 会计年度 **/
  getYear() {
    let data = { 'year': 0, 'company': this.companyId };
    if (this.companyId != null) {
      this.apiService.post('finance.accountingPeriod.fiscalPeriod', { 'body': JSON.stringify(data) }).subscribe(
        (body) => {
          if (body) {
            this.year = body.year;
          } else {
            this.msg.info(body.msg);
          }
        });
    }
  }

  /** 获取 会计期间 **/
  getPeriod() {
    if (this.companyId != null) {
      let data = { 'year': this.yearId == null ? 0 : this.yearId, 'company': this.companyId };
      this.apiService.post('finance.accountingPeriod.fiscalPeriod', { 'body': JSON.stringify(data) }).subscribe(
        (body) => {
          if (body) {
            this.period = body.period;
          } else {
            this.msg.info(body.msg);
          }
        });
    }
  }

  /** 获取 会计期间 **/
  getStopPeriod() {
    if (this.companyId != null) {
      let data = { 'year': this.stopYearId == null ? 0 : this.stopYearId, 'company': this.companyId };
      this.apiService.post('finance.accountingPeriod.fiscalPeriod', { 'body': JSON.stringify(data) }).subscribe(
        (body) => {
          if (body) {
            this.stopPeriod = body.period;
          } else {
            this.msg.info(body.msg);
          }
        });
    }
  }


  /** 获取 科目级别**/
  getAccIdRule() {
    let data = { 'company': this.companyId };
    this.apiService.post('finance.accountingChartDistributionCompany.findByCompany', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.accountClasses = body.accIdRuleArr;
        } else {
          this.msg.info(body.msg);
        }
      },
    );
  }

  getAux() {
    if (this.acc != null) {
      this.aux = [];
      this.auxId = null;
      this.aux = this.acc['aux'];
      if (this.acc['aux'] != null) {
        this.flag = false;
      }
    }
  }

  /** 保留两位小数点 **/
  toFixed(params) {
    let key = params.colDef.field;
    let data = params.data[key];
    if (data !== undefined) {
      data = data.toFixed(2);
    }
    return data;
  }

  getValueFormatter(): string {
    return '\'[\' +value.id+ \']\' + \' \' + value.name';
  }

  getDownFormatter(): string {
    return '\'[\' +value.id+ \']\' + \' \' + value.name';
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      value: value,
    });
  }
}

